package com.cy.module;

import com.alibaba.fastjson.JSONObject;
import com.cy.BasicController;
import com.cy.config.EnumConst;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Account;
import com.cy.model.RoleLabel;
import com.cy.model.User;
import com.cy.shiro.QyUsernamePasswordToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.subject.Subject;

import java.util.List;
import java.util.Map;

@ControllerBind(controllerKey = "/res/_webApi/signin")
public class SigninController extends BasicController {

    public void index() {
        JSONObject obj = new JSONObject();
        Integer code;

        Map<String,String[]> paraMap = getParaMap();
        String account, password, type;
        if (null != paraMap && paraMap.size() >0){
            account = paraMap.get("account")[0];
            password = paraMap.get("password")[0];
            type = paraMap.get("type")[0];
        }else {
            JSONObject map = (JSONObject) getRequestBody();
            account = map.getString("account");
            password = map.getString("password");
            type = map.getString("type");
        }
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password) || StringUtils.isBlank(type) ) {
            code = EnumConst.RetCode.PARAMETER_IS_NULL.getCode();
        } else {
            Subject currentUser = SecurityUtils.getSubject();
            QyUsernamePasswordToken token = new QyUsernamePasswordToken(account, password,type);
            try {
                currentUser.login(token);
                initLogger();
                code = EnumConst.RetCode.SUCCESS.getCode();
                getLog().info("login To :" + account + ",type:"+type+",and success!");
                if ("account".equals(type)){
                    Account loginUser = getLoginAccount();
                    if (loginUser != null) {
                        loginUser.remove("password", "salt");//删除数据（前端）
                        obj.put("account", loginUser);
                    }
                }else if("user".equals(type)){
                    User user = getLoginUser();
                    if (null != user){
                        User resultUser = user.getResultUser();
                        List<RoleLabel> roles = resultUser.getRoles();
                        resultUser.put("roles", roles);
                        obj.put("user", resultUser);
                    }
                }
                obj.put("as",currentUser.getSession().getId());
            } catch (DisabledAccountException disabledAccountException) {
                code = EnumConst.RetCode.ACCOUNT_EXCEPTION.getCode();
                getLog().warn("Login to :" + account + ",type:"+type+"but the account is disable");
            } catch (AuthenticationException authenticationException) {
                code = EnumConst.RetCode.USERNAME_OR_PASSWORD_ERROR.getCode();
                getLog().warn("Login to :" + account + ",type:"+type+" but the account or the password is incorrect");
            }
        }
        if (code != 0) {
            obj.put("code", code);
            renderJson(obj);
        }
    }
    /**
     * 网页登录
     *
     * @post-param mobile   手机号码,登录名
     * @post-param password 密码
     */
    public void loginOk() {
        String account = getPara("account");
        String password = getPara("password");
        if (StringUtils.isNotBlank(account) && StringUtils.isNotBlank(password)) {
            Subject currentUser = SecurityUtils.getSubject();
            QyUsernamePasswordToken token = new QyUsernamePasswordToken(account, password,QyUsernamePasswordToken.Type.ACCOUNT.getValue());
            try {
                currentUser.login(token);
                getLog().info("login To :" + account + ",and success!");
                forwardAction("/clmp/main");
                return;
            } catch (DisabledAccountException disabledAccountException) {
                setAttr("shiroLoginFailure", "DISA");
                getLog().warn("Login to :" + account + ",but the account is disable");
            } catch (AuthenticationException authenticationException) {
                setAttr("shiroLoginFailure", "UNKA");
                getLog().warn("Login to :" + account + ",but the account or the password is incorrect");
            }
        } else {
            setAttr("shiroLoginFailure", "UNKA");
        }
        forwardAction("/");
    }

    /**
     * 用户登出
     */
    public void signout(){
        JSONObject json = new JSONObject();
        Account account = getLoginAccount();
        if(null != account){
            log("signout :" + account.getAccount() + ",and success!");
        }
        SecurityUtils.getSubject().logout();
        json.put("code", EnumConst.RetCode.SUCCESS.getCode());
        renderJson(json);
    }

}
